package com.youaishujuhui.devops.web.service.manage;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youaishujuhui.devops.web.dao.manage.SysRoleDao;
import com.youaishujuhui.devops.web.dao.manage.SysUserDao;
import com.youaishujuhui.devops.web.domain.manage.SysResource;
import com.youaishujuhui.devops.web.domain.manage.SysRole;
import com.youaishujuhui.devops.web.domain.manage.SysUser;

@Service
public class SysUserService {
	
	@Autowired
	private SysUserDao sysUserDao;
	
	@Autowired
	private SysRoleDao sysRoleDao;

	public SysUser getByUserName(String userName) {
		return sysUserDao.getByUserName(userName);
	}
	
	public SysUser insert(String userName) {
		return sysUserDao.insert(userName);
	}

	public int total(Map<String, Object> param) {
		return sysUserDao.total(param);
	}

	public List<SysUser> query(Map<String, Object> param) {
		return sysUserDao.query(param);
	}
	
	public boolean containsResourceUris(String userName, String uri) {
		return getResources(userName).contains(uri);
	}
	
	public SysUser findById(Integer id) {
		return sysUserDao.findById(id);
	}

	public Set<String> getResources(String staffCode) {
		SysUser user = sysUserDao.getByUserName(staffCode);
		user = sysUserDao.fetchRoles(user);
		
		
		List<SysRole> roles = user.getRoles();
		
		Set<String> uris = new HashSet<String>();
		
		if (roles != null) {
			for (SysRole role : roles) {
				role = sysRoleDao.fetchResources(role);
				
				List<SysResource> resources = role.getResources();
				if (resources != null) {
					for (SysResource resource : resources) {
						uris.add(resource.getUri());
					}
				}
			}
		}
		
		return uris;
	}

	public List<SysRole> getRolesList(Integer userId) {
		return sysUserDao.getRolesList(userId);
	}
	
	public void clearRoles(SysUser user) {
		sysUserDao.clearRoles(user);
	}

	public void insertRelation(SysUser user) {
		sysUserDao.insertRelation(user);
	}
}
